package paythere

import (
	"context"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/pay/paythere"
	"gitee.com/liuxuezhan/ar-platform/admin-api/pkg/xerrors/assets"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/assetsClient/rpc"
	"github.com/bytedance/sonic"
	"github.com/zeromicro/go-zero/core/logc"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type PayTherePayoutNotifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// PayThere代付回调通知
func NewPayTherePayoutNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PayTherePayoutNotifyLogic {
	return &PayTherePayoutNotifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PayTherePayoutNotifyLogic) PayTherePayoutNotify(req *types.PayTherePayoutNotifyReq) (resp *types.PayTherePayoutNotifyResp, err error) {
	b, _ := sonic.Marshal(req)
	logc.Info(l.ctx, string(b))
	// 获取 payfun 配置信息
	order, err := l.svcCtx.AssetsRpc.PayWithdraw.WithdrawListPage(l.ctx, &rpc.FindWithDrawReq{OrderNo: req.MerchantOrderNo})
	if err != nil {
		return nil, err
	}
	if len(order.Data) == 0 {
		logc.Error(l.ctx, "order.Data does not exist", string(b))
		return nil, assets.ErrWithdrawPayNoChannel
	}
	if _, ok := order.Data[0].Channel[order.Data[0].WithdrawChannelId]; !ok {
		logc.Error(l.ctx, "order.Data[0].Channel[order.Data[0].WithdrawChannelId] does not exist", string(b))
		return nil, assets.ErrWithdrawPayNoChannel
	}
	// 请求参数
	params := map[string]any{
		"amount":          req.Amount,
		"merchantNo":      req.MerchantNo,
		"merchantOrderNo": req.MerchantOrderNo,
		"platOrderNo":     req.PlatOrderNo,
		"orderStatus":     req.OrderStatus,
		"orderMessage":    req.OrderMessage,
	}
	// 生成签名
	sign, err := paythere.GenerateSignature(params, order.Data[0].Channel[order.Data[0].WithdrawChannelId].SecretKey)
	if err != nil {
		return nil, err
	}
	if sign != req.Sign {
		return nil, assets.ErrSignVerifyFailed
	}
	// 根据订单状态处理业务逻辑
	switch req.OrderStatus {
	case "SUCCESS":
		_, err = l.svcCtx.AssetsRpc.PayWithdraw.WithdrawSuccess(l.ctx, &rpc.SuccessWithDrawReq{OrderNo: req.MerchantNo, Data: string(b)})
		if err != nil {
			logc.Error(l.ctx, err, string(b))
			return
		}
		resp = &types.PayTherePayoutNotifyResp{Ok: true}
	case "FAILED":
		_, err = l.svcCtx.AssetsRpc.PayWithdraw.WithdrawFail(l.ctx, &rpc.FailWithDrawReq{OrderNo: req.MerchantNo, Data: string(b)})
		if err != nil {
			logc.Error(l.ctx, err, string(b))
			return
		}
		resp = &types.PayTherePayoutNotifyResp{Ok: false}
	default:
		resp = &types.PayTherePayoutNotifyResp{Ok: false}
	}
	return
}
